package com.u.social.article.config;

/**
 * @program: u-social
 * @description:
 * @author: Alex Wu
 * @createDate: 2025-03-03 17:24
 **/
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync // 启用异步支持
public class ThreadPoolConfig {

    @Value("${spring.task.execution.pool.core-size}")
    private int corePoolSize;

    @Value("${spring.task.execution.pool.max-size}")
    private int maxPoolSize;

    @Value("${spring.task.execution.pool.queue-capacity}")
    private int queueCapacity;

    @Value("${spring.task.execution.pool.thread-name-prefix}")
    private String threadNamePrefix;

    @Value("${spring.task.execution.pool.await-termination-seconds}")
    private int awaitTerminationSeconds;

    @Value("${spring.task.execution.pool.wait-for-tasks-to-complete-on-shutdown}")
    private boolean waitForTasksToCompleteOnShutdown;

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);  // 核心线程数
        executor.setMaxPoolSize(maxPoolSize);    // 最大线程数
        executor.setQueueCapacity(queueCapacity); // 队列容量
        executor.setThreadNamePrefix(threadNamePrefix); // 线程名称前缀
        executor.setAwaitTerminationSeconds(awaitTerminationSeconds); // 等待所有任务完成的超时时间
        executor.setWaitForTasksToCompleteOnShutdown(waitForTasksToCompleteOnShutdown); // 任务完成后等待关闭线程池
        return executor;
    }
}
